package com.spsoft.vatoutinv.service.vmsavalibletaxrate.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spsoft.core.enums.ResponseEnum;
import com.spsoft.core.model.Result;
import com.spsoft.core.model.bo.TokenUser;
import com.spsoft.core.model.leqidmz.param.BaseNsrRequestParams;
import com.spsoft.core.model.leqidmz.response.QueryAvalibleTaxRateVo;
import com.spsoft.core.utils.BeanUtils;
import com.spsoft.core.utils.ExcelUtils;
import com.spsoft.einvoicetodmz.service.DmzApiClientService;
import com.spsoft.vatoutinv.constants.CommonConstant;
import com.spsoft.vatoutinv.constants.DictConstant;
import com.spsoft.vatoutinv.entity.vmsavalibletaxrate.VmsAvalibleTaxRate;
import com.spsoft.vatoutinv.entity.vmsavalibletaxrate.VmsAvalibleTaxRateLog;
import com.spsoft.vatoutinv.entity.vmsavalibletaxrate.VmsAvalibleTaxRateLogBase;
import com.spsoft.vatoutinv.entity.vmsenterpriseinforisk.VmsEnterpriseInfoRiskLog;
import com.spsoft.vatoutinv.mapper.VmsAvalibleTaxRateLogBaseMapper;
import com.spsoft.vatoutinv.mapper.VmsAvalibleTaxRateMapper;
import com.spsoft.vatoutinv.model.dto.vmsavalibletaxrate.VmsAvalibleTaxRateDto;
import com.spsoft.vatoutinv.model.vo.vmsavalibletaxrate.VmsAvalibleTaxRateVo;
import com.spsoft.vatoutinv.service.translate.impl.DictTranslate;
import com.spsoft.vatoutinv.service.vmsavalibletaxrate.VmsAvalibleTaxRateLogService;
import com.spsoft.vatoutinv.service.vmsavalibletaxrate.VmsAvalibleTaxRateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 可用税率信息查询记录列表表 服务实现类
 * </p>
 *
 * @author chenxudong
 * @since 2023-11-23
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class VmsAvalibleTaxRateServiceImpl extends ServiceImpl<VmsAvalibleTaxRateMapper, VmsAvalibleTaxRate> implements VmsAvalibleTaxRateService {

    public static final String TAX_RATE_MSG = "(可用税率信息实现层)";

    private final DictTranslate dictTranslate;

    private final DmzApiClientService dmzApiClientService;

    private final VmsAvalibleTaxRateMapper vmsAvalibleTaxRateMapper;

    private final VmsAvalibleTaxRateLogService vmsAvalibleTaxRateLogService;

    private final VmsAvalibleTaxRateLogBaseMapper vmsAvalibleTaxRateLogBaseMapper;

    @Override
    public Result<IPage<VmsAvalibleTaxRateVo>> queryVmsAvalibleTaxRate(VmsAvalibleTaxRateDto vmsAvalibleTaxRateDto) {
        // 分页查询
        Page<VmsEnterpriseInfoRiskLog> page = new Page<>(vmsAvalibleTaxRateDto.getPageNo(), vmsAvalibleTaxRateDto.getPageSize());
        IPage<VmsAvalibleTaxRate> IPage = vmsAvalibleTaxRateMapper.queryVmsAvalibleTaxRate(page, vmsAvalibleTaxRateDto);
        // 将数据库返回数据转换为VO返回前端
        IPage<VmsAvalibleTaxRateVo> IPageVo = IPage.convert(item -> {
            VmsAvalibleTaxRateVo vo = new VmsAvalibleTaxRateVo();
            // 转换数据
            BeanUtils.copyBeanProp(vo, item);
            return vo;
        });
        return Result.OK(IPageVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> getVmsAvalibleTaxRateByLq(VmsAvalibleTaxRateDto vmsAvalibleTaxRateDto, TokenUser userInfo) {
        // 调用乐企接口获取可用税率信息
        BaseNsrRequestParams params = new BaseNsrRequestParams();
        params.setNsrsbh(vmsAvalibleTaxRateDto.getNsrsbh());
        params.setCreateUser(userInfo.getUserCode());
        params.setDeptCode(userInfo.getDeptCode());
        Result<QueryAvalibleTaxRateVo> result = dmzApiClientService.queryAvalibleTaxRate(params, null);

        // 先记录日志操作(LOG_BASE)和乐企返回的当次可用税率记录(LOG)
        VmsAvalibleTaxRateLogBase vmsAvalibleTaxRateLogBase = new VmsAvalibleTaxRateLogBase();
        vmsAvalibleTaxRateLogBase.setDeptCode(userInfo.getDeptCode());
        vmsAvalibleTaxRateLogBase.setNsrsbh(vmsAvalibleTaxRateDto.getNsrsbh());
        vmsAvalibleTaxRateLogBase.setCreateTime(new Date());
        vmsAvalibleTaxRateLogBase.setCreateUser(userInfo.getUserCode());
        vmsAvalibleTaxRateLogBase.setCreateUsername(userInfo.getUserName());

        if (ResponseEnum.SUCCESS.getCode().equals(result.getCode())) {
            log.info("{}调用DMZ查询可用税率信息成功", TAX_RATE_MSG);
            QueryAvalibleTaxRateVo data = result.getData();

            vmsAvalibleTaxRateLogBase.setOperateStatus(CommonConstant.STR_01);
            vmsAvalibleTaxRateLogBase.setLogCount(data.getCount());
            vmsAvalibleTaxRateLogBase.setOperateMsg(JSONObject.toJSONString(data));
            // 记录日志操作(LOG_BASE表)
            vmsAvalibleTaxRateLogBaseMapper.insert(vmsAvalibleTaxRateLogBase);

            List<QueryAvalibleTaxRateVo.TaxRateInfo> slzslList = data.getSlzslList();
            if (CollectionUtil.isNotEmpty(slzslList)) {
                // Bean转换
                List<VmsAvalibleTaxRateLog> vmsAvalibleTaxRateLogList = BeanUtils.copyListProperties(slzslList, VmsAvalibleTaxRateLog::new, (s, t) -> {
                    t.setLogBaseId(vmsAvalibleTaxRateLogBase.getId());
                    t.setDeptCode(userInfo.getDeptCode());
                    t.setNsrsbh(vmsAvalibleTaxRateDto.getNsrsbh());
                    t.setCount(data.getCount());
                });
                // 记录乐企返回的当次可用税率记录(LOG表)
                vmsAvalibleTaxRateLogService.saveBatch(vmsAvalibleTaxRateLogList);

                // 保存乐企返回的当次可用税率记录(VMS_AVALIBLE_TAX_RATE表)
                LambdaQueryWrapper<VmsAvalibleTaxRate> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(VmsAvalibleTaxRate::getDeptCode, vmsAvalibleTaxRateDto.getDeptCode());
                baseMapper.delete(queryWrapper);

                List<VmsAvalibleTaxRate> vmsAvalibleTaxRateList = BeanUtils.copyListProperties(slzslList, VmsAvalibleTaxRate::new, (s, t) -> {
                    t.setLogBaseId(vmsAvalibleTaxRateLogBase.getId());
                    t.setDeptCode(userInfo.getDeptCode());
                    t.setNsrsbh(vmsAvalibleTaxRateDto.getNsrsbh());
                    t.setCount(data.getCount());
                    t.setCreateTime(new Date());
                    t.setCreateUser(userInfo.getUserCode());
                    t.setCreateUsername(userInfo.getUserName());
                    t.setUpdateTime(new Date());
                    t.setUpdateUser(userInfo.getUserCode());
                    t.setUpdateUsername(userInfo.getUserName());
                });
                this.saveBatch(vmsAvalibleTaxRateList);
            }
        } else {
            log.error("{}调用DMZ查询可用税率信息失败，原因：{}", TAX_RATE_MSG, result.getMessage());
            vmsAvalibleTaxRateLogBase.setOperateStatus(CommonConstant.STR_02);
            vmsAvalibleTaxRateLogBase.setOperateMsg(result.getMessage());
            vmsAvalibleTaxRateLogBaseMapper.insert(vmsAvalibleTaxRateLogBase);
            return Result.ERROR(result.getCode(), result.getMessage());
        }
        return Result.OK_MSG(ResponseEnum.LEQI_SUCCESS.getMsg());
    }

    @Override
    public void exportVmsAvalibleTaxRate(VmsAvalibleTaxRateDto vmsAvalibleTaxRateDto, HttpServletResponse response) {
        try {
            List<VmsAvalibleTaxRate> vmsAvalibleTaxRateList = vmsAvalibleTaxRateMapper.queryVmsAvalibleTaxRateExport(vmsAvalibleTaxRateDto);
            List<VmsAvalibleTaxRateVo> vmsAvalibleTaxRateVoList = BeanUtils.copyListProperties(vmsAvalibleTaxRateList, VmsAvalibleTaxRateVo::new, (s, t) -> {
                // 导出时需要将字典值转换
                t.setCsxz(dictTranslate.translate(DictConstant.VMS_KYSLCSXZ, s.getCsxz()));
                t.setYslbz(dictTranslate.translate(DictConstant.VMS_YSLBZ, s.getYslbz()));
                t.setCszt(dictTranslate.translate(DictConstant.VMS_KYSLCSZT, s.getCszt()));
            });
            // 添加序号
            for (int i = 0; i < vmsAvalibleTaxRateVoList.size(); i++) {
                vmsAvalibleTaxRateVoList.get(i).setXh(i + 1);
            }
            // 导出
            ExcelUtils.exportExcel(vmsAvalibleTaxRateVoList, VmsAvalibleTaxRateVo.class, "可用税率信息", response);
        } catch (Exception e) {
            log.error("{}出现异常", TAX_RATE_MSG, e);
        }
    }

}
